<template>
    <el-dialog
        :visible="true"
        width="50%"
        :fullscreen="fullScreen"
        :append-to-body="true"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :before-close="handleClose">
        <span slot="title" class="el-dialog__title">
            关联数据
            <i class="el-icon-full-screen iconClass" v-if="!fullScreen" @click="()=>{fullScreen = true}"></i>
            <i class="el-icon-aim iconClass" v-else @click="()=>{fullScreen = false}"></i>
        </span>
        <div class="dialogBody" :style="{height: 280 + ((linkParamsList.length - 1) * 50) + 'px'}">
            <div class="divClass">
                数据关联来源:
                <el-select filterable placeholder="请选择" v-model="linkTableName" :style="{width: '81%'}" @change='linkFormChange'>
                    <el-option
                        v-for="(item, index) in formOptions"
                        :key="index"
                        :label="item.formName"
                        :value="item.tableName"
                    />
                </el-select>
            </div>
            <div class="divClass">
                <el-input style="width:30%" disabled v-model="activeData.__config__.label"></el-input>
                <span class="valueCss1">值等于</span>
                <el-select filterable v-model="linkName" placeholder="请选择关联表单字段" ref="linkVisibleTwo" :style="{width: '30%'}">
                    <el-option
                        v-for="(item, index) in linkFormParamsOptions"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
                的值
            </div>
            <div class="contentCss">
                <div class="divClass" v-for="(linkObj,index) in linkParamsList" :key="index">
                    <el-select filterable v-if="timeStamp" placeholder="请选择当前表单字段" v-model="linkObj.formFieldName" :style="{width: '30%'}" @visible-change="visibleChange">
                        <el-option
                            v-for="(item, index) in curFormParamsOptions"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                            :disabled="item.disabled"
                        />
                    </el-select>
                    <span class="valueCss2">关联显示</span>
                    <el-select filterable placeholder="请选择关联表单字段" v-model="linkObj.sourceFieldName" ref="linkVisibleOne"
                        :style="{width: '30%'}">
                        <el-option
                            v-for="(item, index) in linkFormParamsOptions"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                    中的对应值
                    <el-link style="padding-left:40px;padding-bottom: 3px;" :underline="false" type="primary" @click="addData">添加</el-link>
                    <el-link style="padding-left:15px;padding-bottom: 3px;" :underline="false" type="danger" @click="deleteData(index)">删除</el-link>
                </div>
            </div>
            <!-- <div class="tipClass divClass">
                <i class="el-icon-warning"> 建议：联动的字段类型要跟当前的字段类型一致，否则会出现数据展示不正确的问题。</i>
            </div> -->
            <div class="dialog-footer divClass">
                <el-button size="small" @click="handleClose">取消</el-button>
                <el-button size="small" type="primary" @click="confirm">确定</el-button>
                <el-button size="small" @click="clear">清空</el-button>
            </div>
        </div>
    </el-dialog>
</template>
<script>
import {deepClone} from '../../../../utils/index.js'
import {getPageRelease} from '@/api/custom/formPoster.js'
import {listchoose, sourceTestList} from '@/api/custom/formDesigner'
export default {
    name: 'SettingRelatedDialog',
    data () {
        return {
            fullScreen: false,
            pageInfo: {
                pageNo: 1,
                pageSize: 500
            },
            formOptions: [],
            linkTableName: '',
            curFormParamsOptions: [],
            curFormParamsMap: new Map(),
            linkFormParamsMap: new Map(),
            linkFormParamsOptions: [],
            linkParamsList:[
                {
                    formFieldName: '',
                    sourceFieldName: '',
                }
            ],
            linkName: '',
            timeStamp: Date.now(),
            // 过滤掉不使用联动数据的组件
            filterTag: ['Subform', 'el-tabs', 'TitleLine', 'TitleLine', 'Steps', 'el-switch', 'el-collapse', 'el-card', 'UsersSelector', 'DepartmentSelection', 'PostSelection', 'signature']
        }
    },
    props: ['activeData', 'fields'],
    created () {
        const _this = this
        // 过滤掉不显示关联数据的组件和当前组件
        const useList = this.fields.filter(cur => {
            return !this.filterTag.includes(cur.__config__.tag) && cur.__vModel__ !== this.activeData.__vModel__
        })
        console.log(this.fields,useList,'pppppppppp')
        // 当前表单字段下拉选项
        this.curFormParamsOptions = useList.map(comp => {
            return {
                label: comp.__config__.label,
                value: comp.__vModel__,
            }
        })
        const {linkName, tableName, sysRelationDataList} = this.activeData.__config__.relatedData
        listchoose().then(rsp => {
            if (rsp.code === 0) {
                // 查询所有已发布的表单下拉选项
                this.formOptions = rsp.data.map((item)=>{
                    return {
                        formName:item.name,
                        tableName:item.id
                    }
                })
                // this.formOptions.forEach((item, idx) => {
                //     const jsonObj = JSON.parse(item.formJsonUser)
                //     const newCompList = jsonObj.fields.filter(comp => {
                //         return !this.filterTag.includes(comp.__config__.tag)
                //     })
                //     this.linkFormParamsMap.set(item.tableName, newCompList)
                //     if (tableName === item.tableName) {
                //         this.linkFormParamsOptions = newCompList.map(comp => {
                //             return {
                //                 label: comp.__config__.label,
                //                 value: comp.__vModel__
                //             }
                //         })
                //     }
                // })
            }
        })
        // 初始化赋值
        if (tableName) {
            sourceTestList(tableName).then((res) => {
                if (res.code === 0) {
                    this.linkFormParamsOptions = res.data?.columns.map((item) => {
                        return {label:item.name,value:item.name}
                    })
                }
            })
            this.linkTableName = tableName
            this.linkName = linkName
            // 修改了关联字段的字段名 需重新选择
            let curFormFields = []
            this.curFormParamsOptions.map((item) => {
                curFormFields.push(item.value)
            })
            sysRelationDataList.map((val) => {
                if(curFormFields?.indexOf(val.formFieldName) == -1){
                    val.formFieldName = ''
                }
            })
            this.linkParamsList = [...sysRelationDataList]
        }
    },
    methods: {
        addData () {
            this.linkParamsList.push({
                formFieldName: '',
                sourceFieldName: '',
            })
        },
        deleteData (idx) {
            if (this.linkParamsList.length === 1) {
                this.linkParamsList = []
                this.addData()
                return this.$message.warning('至少需要一个关联关系')
            }
            this.linkParamsList.splice(idx, 1)
        },
        linkFormChange (val) {
            // 切换关联表单，对应联动表单选项变化
            sourceTestList(val).then((res) => {
                if (res.code === 0) {
                    this.linkFormParamsOptions = res.data?.columns.map((item) => {
                        return {label:item.name,value:item.name}
                    })
                }
            })
            this.linkName = ''
            this.linkParamsList.forEach(obj => {
                obj.sourceFieldName = ''
            })
        },
        visibleChange (flag) {
            if (flag) {
                const idList = this.linkParamsList.map(obj => obj.formFieldName)
                this.curFormParamsOptions.forEach(item => {
                    if (idList.includes(item.value)) {
                        item.disabled = true
                    }else{
                        item.disabled = false
                    }
                })
                this.timeStamp = Date.now()
            }
        },
        confirm () {
            if (!this.linkTableName) {
                return this.$message.warning('请选择数据关联来源')
            }
            if (!this.linkName) {
                return this.$message.warning('请选择关联表单字段')
            }
            for (let a = 0; a < this.linkParamsList.length; a++) {
                const temp = this.linkParamsList[a]
                if (!temp.formFieldName) {
                    this.$message.warning('请选择第' + (a + 1) +'行当前表单字段')
                    return
                }
                if (!temp.sourceFieldName) {
                    this.$message.warning('请选择第' + (a + 1) +'行关联表单字段')
                    return
                }
            }
            const obj = {
                curParams: this.activeData.__vModel__,
                sysRelationDataList: [...this.linkParamsList],
                linkName: this.linkName,
                tableName: this.linkTableName, // 关联表单id
            }
            this.$emit('closeRelatedDialog', obj)
        },
        //清空
        clear() {
            this.linkTableName = '' 
            this.linkName = ''
            this.linkParamsList = [
                {
                    formFieldName: '',
                    sourceFieldName: '',
                }
            ]
            this.linkFormParamsOptions = []
            this.$emit('closeRelatedDialog', {})
            handleClose()
        },
        // 关闭弹框
        handleClose () {
            this.$emit('closeRelatedDialog', false)
        },
    }
}
</script>
<style lang="less" scoped>
/deep/.el-dialog__title{
    width: 100%;
}
.contentCss{
    max-height: 400px;
    overflow-y: auto;
}
.valueCss1{
    display:inline-block;
    width:77px;
    text-align:center
}
.valueCss2{
    display:inline-block;
    width:80px;
    text-align:center
}
.divClass{
    margin: 15px 0px;
}
.dialog-footer{
    float: right;
}
.tipClass{
    background-color: oldlace;
    color: orange;
    height: 28px;
    line-height: 28px;
    padding-left: 10px;
    font-size: 12px;
}
/deep/.el-button--medium {
    padding: 0px 20px;
    margin-top: 85px;
}
.iconClass{
    float:right;
    margin-right:25px;
    line-height: 1.5;
}
/deep/.el-dialog{
    width: 45% !important;
}
/deep/.el-dialog__body{
    max-height: 610px;
    padding: 0px 20px;
}
::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 5px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 5px;
}
::-webkit-scrollbar-thumb {
  background-color: skyblue;
  background-image: -webkit-linear-gradient(
    45deg,
    rgba(255, 255, 255, 0.2) 25%,
    transparent 25%,
    transparent 50%,
    rgba(255, 255, 255, 0.2) 50%,
    rgba(255, 255, 255, 0.2) 75%,
    transparent 75%,
    transparent
  );
  /*滚动条里面小方块*/
  border-radius: 10px;
}
::-webkit-scrollbar-track {
  background: #ededed;
  border-radius: 10px;
  /*滚动条里面轨道*/
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
}
</style>